/*
 * 数据插入
 */
package io.github.ilkgunel.operations;

import io.github.ilkgunel.database.AccessMongoDB;
import org.bson.Document;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *
 * @author ilkaygunel
 */
@WebServlet(name = "test3_3", urlPatterns = {"/test3_3"})
public class test3_3 extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //processRequest(request, response);
        String insertMessage = "";

        String cid= request.getParameter("cid");
        String name = request.getParameter("name");
        String fcid = request.getParameter("fcid");
        double credit = Double.parseDouble(request.getParameter("credit"));

        AccessMongoDB accessMongoDB = new AccessMongoDB();

        try {
            accessMongoDB.getCollection("course").insertOne(
                    new Document()
                    .append("cid",cid )
                    .append("name", name)
                    .append("fcid", fcid)
                    .append("credit",credit)

            );
            insertMessage = "课程成功插入啦!";
            System.out.println(insertMessage);
        } catch (Exception e) {
            insertMessage = "插入有错误:"+e;
            System.out.println(insertMessage);
        }
        request.setAttribute("insertMessage", insertMessage);
        int index=request.getHeader("Referer").indexOf("test");
        RequestDispatcher dispatcher = request.getRequestDispatcher(request.getHeader("Referer").substring(index));
        dispatcher.forward(request, response);
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String insertMessage = "";
        request.setAttribute("insertMessage", insertMessage);
        int index=request.getHeader("Referer").indexOf("test");
        RequestDispatcher dispatcher = request.getRequestDispatcher(request.getHeader("Referer").substring(index));
        dispatcher.forward(request, response);
    }
}
